<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Db;

class Driver Extends Base
{
    protected $id    = 'driver_id';
    protected $table = 'driver';
    protected $joins = [['car c','c.car_id = m.car_id','left'],['company cr','cr.company_id = m.company_id','left'],['user u','u.user_id = m.user_id','left']];
    protected $field = 'm.*,c.number,cr.company_name,u.username,u.mobile AS phone';

    public function stat() {

        //搜索
        $start = input('param.start','1970-01-01');
        $end = input('param.end',date('Y-m-d'));
        $start = $start ?: '1970-01-01';
        $end = $end ?: date('Y-m-d',strtotime("+1 days"));

        //时间段
        $time = input('param.time');
        if($time == 'day') {
            $start = date('Y-m-d');
        } elseif($time == 'month') {
            $start = date('Y-m-01');
        } elseif($time == 'year') {
            $start = date('Y-01-01');
        }

        $company = input('param.company_id');
        $name = input('param.name');
        $count = [];
        //用车公司搜索

        $order = Db::name('order')->alias('o')->whereNull('o.delete_time')->where('o.order_time','>=',$start)->where('o.order_time','<=',$end);
        $driver = Db::name('driver')->alias('d')->whereNull('d.delete_time');
        //
//		$json = file_get_contents('http://new.jjcxfw.com/api/driver.index/getRedisDriver');
//		$json = json_decode($json,1);
        $count['online'] = count($json['data']);

        if($name) {
            $driver->where('name','like',"%{$name}%");
            $order->join('driver d','d.driver_id = o.driver_id')->where('d.name','like',"%{$name}%");
        } elseif($company) {
            $driver->join('company cr','cr.company_id = d.company_id')->where('cr.company_id',$company);
            $order->join('driver d','d.driver_id = o.driver_id')->join('company cr','cr.company_id = d.company_id')->where('cr.company_id',$company);
        }

        //司机
        $drivers = $driver->select();
        $orders = $order->select();

        //总数
        $count['qty'] = count($drivers);
        $driver_ids = array_column($drivers,'driver_id');
        foreach($drivers As $d) {
            if( $d['work_state'] > 1 ) {
                $count['online']++;
            }
        }
        //在线
//		halt($count);
        //运行里程
        $count['km'] =   array_sum( array_column($orders,'actual_mileage'));
        $count['km_last'] = $count['km'] - intval($count['km']*0.05);
        $count['water'] = array_sum( array_column($orders,'settlement_price'));
        $count['water_last'] = $count['water'] - intval($count['water']*0.05);
        //接单数
        $count['orders'] = count($orders);

        foreach($orders AS $o) {
            if($o['order_state'] == 12) {
                $count['cancel']++;
            } elseif($o['order_state'] == 11) {
                $count['finish']++;
            }
        }

        $count['orders_last'] = $count['orders'] - intval($count['orders']*0.05);
        $count['cancel_last'] = $count['cancel'] - intval($count['cancel']*0.05);
        $count['finish_last'] = $count['finish'] - intval($count['finish']*0.05);

        //投诉
        $count['complaint'] = Db::name('complaint')->count();
        $count['complaint_last'] = $count['complaint'] - intval($count['complaint']*0.05);
//		halt($count);
        $this->assign('item',$count);
        //司机
        return $this->out();
    }

    public function bind() {

        $driver_id = input('post.driver_id');
        $car_id = input('post.car_id');
        $rslt = Db::name('Driver')->where('driver_id',$driver_id)->setField('car_id',$car_id);

        return $this->res($rslt);
    }

    //绑定

    public function unbind() {

        $driver_id = input('post.driver_id');
        $car_id = input('post.car_id');
        $rslt = Db::name('Driver')->where('driver_id',$driver_id)->setField('car_id',0);

        return $this->res($rslt);
    }
    //解除绑定

    public function delete() {

        $id = input('post.id/a');

        if($id) {
            //查询用户ID
            $uids = Db::name($this->table)->whereIn($this->id,$id)->column('user_id');
            $rslt = Db::name('user')->whereIn('user_id',$uids)->setField('delete_time',time());

//			if(is_array($id)) $id = implode(',',$id);
            if($rslt) {
                $rslt = Db::name($this->table)->whereIn($this->id,$id)->setField('delete_time',time());
            } else {
                Db::name('user')->whereIn('user_id',$uids)->setField('delete_time',null);
            }

        }

        return $this->res($rslt);

    }

    //删除 

    public function outexcel() {

        $P = input('param.');
        $where = [];

        $P['work_state'] && $where['work_state'] = ['=',$P['work_state']];
        $P['company_id'] && $where['company_id'] = ['=',$P['company_id']];
        $P['name'] && $where['name'] = ['=',$P['name']];
        $P['phone'] && $where['phone'] = ['=',$P['phone']];
        $P['c-number'] && $where['c-number'] = ['LIKE',"%{$P['c-number']}%"];

        $driver_return = Db::name('driver')->where($where)->whereNull('delete_time')->field('name,id_card,phone,age,language,original_position,sex,company_id,birthday,driving_age,bank,bank_card,wechat,alipay,driver_no,add')->order('register_time desc')->select();
        $company_return = Db::name('company')->where('')->whereNull('delete_time')->field('company_name,company_id')->select();
        $driver_account_return = Db::name('driver_account')->where('')->field('driver_id,balance')->select();

        if($driver_return) {
            //标题
            $title = array("姓名","身份证号","手机号","年龄","掌握语言","原职位","性别","所属公司","出生年月","驾龄（年）","银行名称","银行帐号","微信账号","支付宝帐号","司机工号","现居住地址");
            //文件名
            $filename = '司机管理导出报表';
            header("Content-type:application/octet-stream");
            header("Accept-Ranges:bytes");
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition:attachment;filename=".$filename.".xls");
            header("Pragma: no-cache");
            header("Expires: 0");
            echo "<table border='1'>";
            if (!empty($title)) {
                foreach ($title as $k => $v) {
                    $title[$k] = iconv("UTF-8", "GB2312", "<td>".$title[$k]."</td>");
                    echo $title[$k];
                }
                //$title = implode("\t", $title);
                //echo "$title".PHP_EOL;
                echo "</tr>";
            }
            if (!empty($driver_return)) {
                foreach ($driver_return as $key => $val) {
                    echo "<tr>";

                    if($driver_return[$key]['sex'] == '1'){
                        $driver_return[$key]['sex'] = '男';
                    }
                    elseif ($driver_return[$key]['sex'] == '2'){
                        $driver_return[$key]['sex'] = '女';
                    }

                    $driver_return[$key]['language'] = str_ireplace("0","",$driver_return[$key]['language']);
                    $driver_return[$key]['language'] = str_ireplace("1","普通话",$driver_return[$key]['language']);
                    $driver_return[$key]['language'] = str_ireplace("2","闽南话",$driver_return[$key]['language']);
                    $driver_return[$key]['language'] = str_ireplace("3","广东话",$driver_return[$key]['language']);
                    $driver_return[$key]['language'] = str_ireplace("4","英语",$driver_return[$key]['language']);
                    $driver_return[$key]['language'] = str_ireplace("5","日语",$driver_return[$key]['language']);
                    $driver_return[$key]['language'] = str_ireplace("6","韩语",$driver_return[$key]['language']);

                    foreach ($company_return as $key2 => $val2) {
                        if($driver_return[$key]['company_id'] == $company_return[$key2]['company_id']){
                            $driver_return[$key]['company_id'] = $company_return[$key2]['name'];
                        }
                    }

                    foreach ($val as $ck => $cv) {
                        $driver_return[$key][$ck] = iconv("UTF-8", "GB2312", "<td style=\"vnd.ms-excel.numberformat:@\">".$driver_return[$key][$ck]."</td>");
                        echo $driver_return[$key][$ck];
                    }
                    //$driver_return[$key] = implode("\t", $driver_return[$key]);
                    echo "</tr>";
                }
                //echo implode(PHP_EOL, $driver_return);
            }
        }
        else {
            $this->error('无数据');
        }
    }

    protected function parseData($data) {

        $data = parent::parseData($data);
        unset($data['username']);

        //取消 BY发仔 2018-07-17
//	    $company_id = $data['company_id'];
//	    $userId      = $data['user_id'];
//	    if($userId==0){
//	        $user = [];
//	        $user['salt'] = substr(uniqid(), -6);
//	        $user['password'] = CorePwd('111111',$user['salt']);
//	        $user['role_id']  = 5;
//	        $user['username'] = $data['phone'];
//	        $user['mobile']   = $data['phone'];
//	        $user['area_id']  = Db::name('company')->where('company_id',$company_id)->value('area_id');
//	        $repeat = Db::name('user')->where('username|mobile',$data['phone'])->whereNull('delete_time')->find();
//	        if($repeat) {
//	            return $this->error('手机已存在，用户添加失败，请修改手机');
//	        }
//	        $data['user_id'] = Db::name('user')->insertGetId($user);
//	    } elseif($data['password']) {
//	        $user['salt'] = substr(uniqid(), -6);
//	        $user['password'] = CorePwd($data['password'],$user['salt']);
//
//	        Db::name('user')->where('user_id',$userId)->update($user);
//
//	    }
//	    $data['edit_time'] = time();
//	    unset($data['password']);
        return $data;
    }

    protected function info() {
        $driver_id = input('post.driver_id');
        $car_id = input('post.car_id');

        $this->relation = ['driver_id'=>$driver_id,'car_id'=>$car_id];

        //是否已经绑定
        $this->bind = Db::name('DriverCar')->where($this->relation)->find();

    }

    protected function options($item = []) {

        $this->assign('work_states',config('base.work_states'));
        $this->assign('languages',TplOptions( config('base.languages'),$item['language'] ));

        $languages = config('base.languages');
        if(!empty($item['language'])){
            $temp = explode(',',$item['language']);
            foreach($temp AS $l) {
                $item['languages'][] = $languages[$l];
            }
            $item['languages'] = implode(',',$item['languages']);
        }
        if(!empty($item['company_id'])){
            $item['company_name'] = Db::name('company')->where('company_id',$item['company_id'])->value('company_name');
        }

        $this->assign('item',$item);
        return $item;
    }


}
